package com.poc.common.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.PowerManager;
import android.provider.Settings;

import com.itsdf07.alog.ALog;


/**
 * @Description ：电池相关工具类
 * @Author itsdf07
 * @Time 2018/2/23
 */

public class BatteryUtils {
    public static final int BATTERY_OPTIMIZATION_MODEL_SYSTEM = 0;
    public static final int BATTERY_OPTIMIZATION_MODEL_CUSTOM = 1;
    private static final String TAG = "BatteryUtils";

    /**
     * Android 6.0开始针对Doze模式添加白名单
     *
     * @param activity
     * @param model
     */
    public static void addWhiteList(Activity activity, int model) {
        if (activity == null) {
            return;
        }
        Intent intent = new Intent();
        if (BATTERY_OPTIMIZATION_MODEL_SYSTEM == model) {
            //方法一
            intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:" + activity.getPackageName()));
        } else if (BATTERY_OPTIMIZATION_MODEL_CUSTOM == model) {
            //方法二，跳到相应的设置页面用户自己去设置
            intent.setAction(android.provider.Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
        }
        try {
            activity.startActivity(intent);
        } catch (Exception e) {
            //坚果Pro机型，7.1.1固件抛出异常：android.content.ActivityNotFoundException
            ALog.eTag("Battery", "e = %s", e.toString());
        }
    }

    /**
     * 当前app是否已在电池优化白名单里面
     *
     * @param activity
     * @return {@code true} 已忽略电池优化 <br> {@code false}  未忽略电池优化
     */
    public static boolean isIgnoringBatteryOptimizations(Activity activity) {
        if (activity == null) {
            //上下文异常时，默认为忽略电池优化，无效引导设置
            return true;
        }
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            //6.0以下默认为忽略电池优化
            return true;
        }

        PowerManager powerManager = (PowerManager) activity.getSystemService(Context.POWER_SERVICE);
        return powerManager.isIgnoringBatteryOptimizations(activity.getPackageName());
    }
}
